/**
 * 模态弹窗
 * @param {*} title 标题
 * @returns 结果
 */
export const uModal = (title = "确定要删除吗?") =>
  new Promise((resolve, reject) =>
    uni.showModal({
      title,
      success(res) {
        resolve(res.confirm);
      },
      fail() {
        reject("error");
      },
    })
  );

/**
 * 获取缓存
 * @param {*} key 键
 * @returns  值
 */
export const uGetStorageSync = (key) => uni.getStorageSync(key);

/**
 * 设置缓存
 * @param {*} key  键
 * @param {*} value  值
 * @returns
 */
export const uSetStorageSync = (key, value) => uni.setStorageSync(key, value);
export const uRemoveStorageSync = (key) => uni.removeStorageSync(key);

/**
 * 显示toast
 * @param {*} title  标题
 * @param {*} icon  图标
 * @param {*} duration 时间
 * @returns
 */
export const uToast = (
  title = "操作成功!",
  icon = "success",
  duration = 2000
) =>
  new Promise((resolve, reject) =>
    uni.showToast({
      title,
      icon,
      duration,
      success() {
        resolve(true);
      },
      fail() {
        reject(false);
      },
    })
  );

/**
 * 上传图片
 * @param {*} url
 * @returns
 */
export const uUploadImage = async (url) => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        console.log("res.tempFilePaths", res.tempFilePaths);
        res.tempFilePaths.forEach((e) => {
          uni.uploadFile({
            url,
            filePath: e,
            name: "file",
            header: {
              "content-type": "multipart/form-data; charset=utf-8",
              //   Authorization: "Bearer " + uni.getStorageSync("token"),
              //   systemAppId: uni.getStorageSync("systemAppId"),
            },
            success: (uploadFileRes) => {
              var jsonData = JSON.parse(uploadFileRes.data);
              if (jsonData.code == 0) {
                console.log("jsonData", jsonData);
                resolve(jsonData.data.src);
              } else {
                reject("图片上传失败");
              }
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      fail: (err) => {
        console.log("err: ", err);
        // #ifdef APP-PLUS
        if (err["code"] && err.code !== 0 && this.sourceTypeIndex === 2) {
          this.checkPermission(err.code);
        }
        // #endif
        // #ifdef MP
        if (err.errMsg.indexOf("cancel") !== "-1") {
          return;
        }
        uni.getSetting({
          success: (res) => {
            let authStatus = false;
            switch (this.sourceTypeIndex) {
              case 0:
                authStatus = res.authSetting["scope.camera"];
                break;
              case 1:
                authStatus = res.authSetting["scope.album"];
                break;
              case 2:
                authStatus =
                  res.authSetting["scope.album"] &&
                  res.authSetting["scope.camera"];
                break;
              default:
                break;
            }
            if (!authStatus) {
              uni.showModal({
                title: "授权失败",
                content:
                  "Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限",
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                },
              });
            }
          },
        });
        // #endif
      },
    });
  });
};

/**
 * 上传文件
 * @param {*} filePath 文件路径
 * @param {*} url 服务器地址
 * @returns 文件在服务器地址
 */
export const uUploadFile = async (filePath, url) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url,
      filePath,
      name: "file",
      header: {
        "content-type": "multipart/form-data; charset=utf-8",
        // token: tokenBear,
      },
      success: (uploadFileRes) => {
        var jsonData = JSON.parse(uploadFileRes.data);
        if (jsonData.code == 0) {
          console.log("jsonData", jsonData);
          resolve(jsonData.data.src);
        } else {
          reject("文件上传失败");
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

/**
 * 加载中。。。
 * @param {*} title
 * @returns
 */
export const uShowLoading = async (title = "加载中。。。") =>
  uni.showLoading({
    title,
  });

/**
 * 隐藏加载中。。。
 * @returns
 */
export const uHideLoading = async () => uni.hideLoading();

/**
 * 导航到
 * @param {*} url 地址
 * @returns
 */
export const uNavigateTo = (url) =>
  uni.navigateTo({
    url,
  });

/**
 * 重定向
 * @param {*} url 地址
 * @returns
 */
export const uReLaunch = (url) =>
  uni.reLaunch({
    url,
  });

/**
 * 重定向
 * @param {*} url 地址
 * @returns
 */
export const uRedirectTo = (url) =>
  uni.redirectTo({
    url,
  });

/**
 * 返回上一级
 * @param {*} delta
 * @returns
 */
export const uNavigateBack = (delta = 1) =>
  uni.navigateBack({
    delta,
  });

/**
 * 导航到tab
 * @param {*} url tab页面地址
 * @returns
 */
export const uSwitchTab = (url) =>
  uni.switchTab({
    url,
  });

/**
 *设置导航栏标题
 * @param {*} title
 * @returns
 */
export const uSetNavigationBarTitle = (title) =>
  uni.setNavigationBarTitle({
    title,
  });

/**
 *预览图片(一张)
 * @param {*} url
 * @returns
 */
export const uPreviewImage = (url) =>
  uni.previewImage({
    urls: [url],
  });

/**
 *预览图片 （多张）
 * @param {*} url
 * @returns
 */
export const uPreviewImages = (urls = []) =>
  uni.previewImage({
    urls,
  });

/**
 * 扫码二维码
 * @returns 扫描结果
 */
export const uScanCode = () =>
  new Promise((resolve, reject) => {
    uni.authorize({
      scope: "scope.camera",
      success() {
        uni.scanCode({
          success(res) {
            if (res.result) {
              resolve(res.result);
            } else {
              reject("授权失败！");
            }
          },
          fail() {
            // 调用相机失败
            uni.showToast({
              title: "调用相机失败",
              icon: "none",
            });
          },
        });
      },
      fail() {
        // 用户拒绝授权
        uni.showToast({
          title: "您拒绝了授权",
          icon: "none",
        });
        reject("您拒绝了授权");
      },
    });
  });

/**
 * 订阅推送消息
 * @param tmplIds 模板ID数组
 */
export async function uRequestSubscribeMessage(tmplIds = []) {
  return new Promise((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds: tmplIds, // 数组，最多3个订阅
      success(res) {
        console.log("订阅消息结果", res);
        resolve(true);
        // 处理订阅消息的结果
      },
      error() {
        reject(false);
      },
    });
  });
}
